package com.thinkgem.jeesite.common.utils.email;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * 读取XML的类
 * 
 * @author admin
 * @version 2017年1月6日
 */
public class XMLUtils {
	
	/**
	 * 读取XML文件的内容
	 * @param path
	 * @return
	 */
	public static String reader(String path) {
		SAXReader reader = new SAXReader();
		reader.setEncoding("UTF-8");
		String str = null;
		try {
			Document d = reader.read(new File(path));
			Element e = d.getRootElement();
			Element htmle = e.element("html");
			str = htmle.asXML();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return str;
	}
	
	/**
	 * 修改XML文件的内容
	 */
	public static void addDiv(String path, int num) {
		SAXReader reader = new SAXReader();
		//reader.setEncoding("UTF-8");
		//path.getBytes();
		Document d = null;
		try {
			d = reader.read(new File(path));
			Element e = d.getRootElement();
			/*Element htmle = e.element("html");
			Element bodye = htmle.element("body");
			Element dive = bodye.element("div");*/
			Element div = e.elementByID("content");
			div.clearContent();
			for(int i=0; i<num; i++) {
				Element divError = div.addElement("div");
				divError.addText("{"+ i +"}");
			}
			writeToNewXMLDocument(d,path);
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}
	
	 /**
     * 通过document对象将内存中的dom树保存到新的xml文档。
     * 
     * @param document
     * @throws Exception
     */
	public static void writeToNewXMLDocument(Document document, String path)
            throws Exception {
		OutputFormat format=OutputFormat.createPrettyPrint();	//使生成的XML自动换行
		format.setEncoding("UTF-8");//utf-8编码
        XMLWriter writer = new XMLWriter(new FileOutputStream(path), format);
        writer.write(document);
        writer.close();
    }

	
}
